import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Checkbox } from './ui/checkbox';
import { FiUpload } from 'react-icons/fi';
import { getVsCodeApi } from '../lib/vscode-api';
import type { MiniProgramCI } from 'miniprogram-ci/dist/@types/types';

interface UploadSectionProps {
  projectPath: string;
  privateKeyPath: string;
  appid: string;
  type: string;
  showToast: (title: string, description: string, type: 'success' | 'error' | 'info') => void;
  setLoading: (loading: boolean) => void;
}

const UploadSection: React.FC<UploadSectionProps> = ({
  projectPath,
  privateKeyPath,
  appid,
  type,
  showToast,
  setLoading,
}) => {
  const [version, setVersion] = useState<string>('1.0.0');
  const [desc, setDesc] = useState<string>('');
  const [robot, setRobot] = useState<number>(1);
  const [threads, setThreads] = useState<number>(1);
  const [settings, setSettings] = useState({
    es6: true,
    es7: false,
    minifyJS: true,
    minifyWXML: true,
    minifyWXSS: true,
    minify: true,
    codeProtect: false,
    autoPrefixWXSS: true,
  });
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [uploadStatus, setUploadStatus] = useState<MiniProgramCI.ITaskStatus | null>(null);

  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      const message = event.data;
      
      switch (message.command) {
        case 'uploadProgress':
          if (message.data) {
            const taskStatus = message.data as MiniProgramCI.ITaskStatus;
            setUploadStatus(taskStatus);
            
            // 根据状态估算进度百分比
            let progressValue = 0;
            switch (taskStatus.status) {
              case 'doing':
                progressValue = 50;
                break;
              case 'done':
                progressValue = 100;
                break;
              case 'fail':
                progressValue = 0;
                break;
              case 'warn':
                progressValue = 75;
                break;
              case 'info':
                progressValue = 25;
                break;
              default:
                progressValue = 0;
            }
            setUploadProgress(progressValue);
            
            // 显示状态消息
            if (taskStatus.message) {
              showToast('上传中', taskStatus.message, 'info');
            }
          }
          break;
          
        case 'uploadResult':
          setLoading(false);
          if (message.data.success) {
            showToast(
              '上传成功',
              `版本 ${version} 已成功上传`,
              'success'
            );
          } else {
            showToast(
              '上传失败',
              message.data.error || '上传过程中发生错误',
              'error'
            );
          }
          break;
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [version, showToast, setLoading]);

  const validateSettings = () => {
    if (!projectPath) {
      showToast('配置不完整', '请先设置项目路径', 'error');
      return false;
    }

    if (!privateKeyPath) {
      showToast('配置不完整', '请先设置私钥路径', 'error');
      return false;
    }

    if (!appid) {
      showToast('配置不完整', '请先设置 AppID', 'error');
      return false;
    }

    if (!version) {
      showToast('版本号为空', '请输入版本号', 'error');
      return false;
    }

    return true;
  };

  const handleSettingChange = (key: keyof typeof settings) => {
    setSettings(prev => ({ ...prev, [key]: !prev[key] }));
  };

  const handleUpload = async () => {
    if (!validateSettings()) return;

    setLoading(true);
    
    // 发送上传请求到扩展
    getVsCodeApi().postMessage({
      command: 'upload',
      data: {
        projectPath,
        privateKeyPath,
        appid,
        type,
        version,
        desc,
        settings,
        robot,
        threads
      }
    });
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>上传代码</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="version">版本号</Label>
          <Input
            id="version"
            value={version}
            onChange={(e) => setVersion(e.target.value)}
            placeholder="例如: 1.0.0"
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="desc">版本描述</Label>
          <Input
            id="desc"
            value={desc}
            onChange={(e) => setDesc(e.target.value)}
            placeholder="请输入版本描述"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="robot">CI 机器人编号 (1-30)</Label>
            <Input
              id="robot"
              type="number"
              min="1"
              max="30"
              value={robot}
              onChange={(e) => setRobot(Number(e.target.value))}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="threads">编译线程数</Label>
            <Input
              id="threads"
              type="number"
              min="1"
              value={threads}
              onChange={(e) => setThreads(Number(e.target.value))}
            />
          </div>
        </div>

        <div className="space-y-2">
          <Label>编译设置</Label>
          <div className="grid grid-cols-2 gap-2 mt-2">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="es6"
                checked={settings.es6}
                onCheckedChange={() => handleSettingChange('es6')}
              />
              <Label htmlFor="es6">ES6 转 ES5</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="es7"
                checked={settings.es7}
                onCheckedChange={() => handleSettingChange('es7')}
              />
              <Label htmlFor="es7">增强编译</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="minifyJS"
                checked={settings.minifyJS}
                onCheckedChange={() => handleSettingChange('minifyJS')}
              />
              <Label htmlFor="minifyJS">压缩 JS</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="minifyWXML"
                checked={settings.minifyWXML}
                onCheckedChange={() => handleSettingChange('minifyWXML')}
              />
              <Label htmlFor="minifyWXML">压缩 WXML</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="minifyWXSS"
                checked={settings.minifyWXSS}
                onCheckedChange={() => handleSettingChange('minifyWXSS')}
              />
              <Label htmlFor="minifyWXSS">压缩 WXSS</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="minify"
                checked={settings.minify}
                onCheckedChange={() => handleSettingChange('minify')}
              />
              <Label htmlFor="minify">压缩所有代码</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="codeProtect"
                checked={settings.codeProtect}
                onCheckedChange={() => handleSettingChange('codeProtect')}
              />
              <Label htmlFor="codeProtect">代码保护</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Checkbox
                id="autoPrefixWXSS"
                checked={settings.autoPrefixWXSS}
                onCheckedChange={() => handleSettingChange('autoPrefixWXSS')}
              />
              <Label htmlFor="autoPrefixWXSS">样式自动补全</Label>
            </div>
          </div>
        </div>
      </CardContent>
      <CardFooter>
        <div className="w-full space-y-2">
          {uploadStatus && (
            <div className="space-y-1">
              <div className="flex justify-between text-sm">
                <span>{uploadStatus.message || '上传中...'}</span>
                <span>{Math.round(uploadProgress)}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                  style={{ width: `${uploadProgress}%` }}
                ></div>
              </div>
            </div>
          )}
          <Button onClick={handleUpload} className="flex items-center w-full">
            <FiUpload className="h-4 w-4 mr-2" />
            上传代码
          </Button>
        </div>
      </CardFooter>
    </Card>
  );
};

export default UploadSection;
